<?php
namespace API\Controller;

use API\Model\UserModel;
use Common\Tool\Tool;
use API\Model\MemberModel;

/**
 * 登录 
 */
class LoginController extends BaseController
{
    /**
     * 登录 
     */
    public function login()
    {
        Tool::checkPost($_POST, array('token'), false , array('username', 'password')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        $_POST['password'] = md5(trim($_POST['password']));
        
        $isSuccess = UserModel::getInistnation()->login($_POST);
        
        $status    = !empty($isSuccess) ? 200 : 400;
        
        $message   = !empty($isSuccess) ? '登陆成功' : '登录失败';
        
        $this->ajaxReturnData($isSuccess ? array($isSuccess) : null, $status, $message);
    }
    
    public function isLogin()
    {
        if(empty($_SESSION['userId']) ) {
            $this->ajaxReturnData(null, '400', '请登录');
        } else {
            $this->ajaxReturnData(array('token' => md5(session_id())));
        }
    }
    /**
     * 退出 
     */
    public function logOut()
    {
        unset($_SESSION['userId']);
        
        $this->ajaxReturnData(null);
    }
    
    /**
     * 发送验证码
     */
    public function sendCode()
    {
       //检测传值
       Tool::checkPost($_POST, (array)null, false , array('mobile')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
       $information = self::send_sms($_POST['mobile']);

       
       $this->updateClient($information ? array(array('sms_code' => $information)) : null, '发送');
    }
    
    /**
     * 是否开启短信验证 
     */
    public function isOpenSms()
    {
        //获取短信配置
        $data   = parent::getConfig();
        $status = $data['sms_open'] == 0 ? '0' : '1';
        $this->ajaxReturnData(array(
            'sms_open' => $status
        ), 200, '操作成功');
    }
    
    /**
     * 短信验证函数封装
     */
    public static function send_sms($mobile)
    {
        //生成随机数
        Tool::connect('PassMiMi');
    
        $verfity = Tool::getSmsCode();
        //获取短信配置
        $data = parent::getConfig();
        if (empty($data))
        {
           return false;
        }
        //以下信息自己填以下
        $argv = array(
            'name'=> $data['account'],     //必填参数。用户账号
            'pwd'=>  $data['sms_pwd'],     //必填参数。（web平台：基本资料中的接口密码）
            'content'=>str_replace('[xxx]', $verfity, $data['sms_content']),  //必填参数。发送内容（1-500 个汉字）UTF-8编码
            'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
            'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
            'sign'=>'【'.mb_substr( strrchr($data['sms_content'], '，'), 1, 4, 'UTF-8').'】',    //必填参数。用户签名。
            'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
        );
        $flag = 0;
        foreach ($argv as $key=>$value) {
            if ($flag != 0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.= urlencode($value);// urlencode($value);
            $flag = 1;
        }
        $url = $data['sms_intnet'].'?'.$params; //提交的url地址
        //连接短信工具
        Tool::connect('Mosaic');
        $smsInformation = Tool::requestSms($url, array('type' => 'pt'));
       
        if ($smsInformation)
        {
            //设置sms_code 保存时间
            S('sms_code', $verfity, 120);
        }
       
        return $smsInformation ? $verfity : false;
    }
    /**
     * 注册 
     */
    public function register()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('mobile'), 'id'), false , array('mobile',/*'idcard','sms_code'*/ 'password')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        //验证手机号码
        Tool::connect('ParttenTool');
        
        $status = Tool::validateData($_POST['mobile'], 'mobile');
        
        $this->prompt($status, null, '手机号码不正确');
        
        $_POST['password'] = md5(trim($_POST['password']));
        
        $result = UserModel::getInistnation()->isRegister($_POST['mobile']);
        
        if ($result>0) {
            $this->ajaxReturnData(null, 400, '账号已经被注册过');
        }
        
        //获取短信配置
        $sms_open = parent::getConfig('sms_open');
        //判断验证码是否正确
        if ($sms_open ==0 &&  S('sms_code') != $_POST['sms_code']) {
            $this->ajaxReturnData(null, 400, '抱歉，请输入正确的验证码或验证码已过期');
        }
        //添加用户到user表
        $isAdd = UserModel::getInistnation()->add($_POST);
        
        $this->prompt($isAdd,null, '添加失败');
        
        $_POST['user_id'] = $isAdd;
        
        $isHave = MemberModel::getInitnation()->add($_POST);
        
        $isAdd && $isHave ? : $this->ajaxReturnData(null, 400 , '添加失败');
        
        //找到推荐人的id 如果没有,不允许注册.
        if (!empty($_POST['id']) &&  $tjId = MemberModel::getInitnation()->getTj($_POST['id']))
        {
            //添加用户到VIP表
            //$sql = "INSERT INTO vip_member(id,pid,mobile,true_name,card_id,create_time,status) VALUES (null,'$pid','$mobile','$realname','$idcard',NOW(),1)";
           
            //找到添加后的用户VIP表中的userid;
           //修改VIP表中的层级关系字段path
           //      $sql = "UPDATE vip_member SET path='$path',user_id='$path_id' WHERE id = '$path_id'";
            $updateSuccess = MemberModel::getInitnation()->save($tjId, array(
                'childrenId' => $isHave
            ));
            $this->updateClient($updateSuccess, '添加');
        }
        $this->ajaxReturnData(null);
    }
    //忘记密码
    public function forgetPassword()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('mobile')),true, array('mobile')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
         
        //是否存在
         
        $isHave = UserModel::getInistnation()->isHaveUserByUserName($_POST['mobile']);
        $this->updateClient($isHave, '验证', true);
    }
     
    /**
     * 重置密码
     */
    public function reset()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('mobile', 'sms_code')),true, array('mobile','sms_code','password')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
         
        if (S('sms_code') != $_POST['sms_code'])
        {
            $this->prompt(null, null, '验证码不正确');
        }
        $_POST['password'] = md5($_POST['password']);
        $status = UserModel::getInistnation()->save($_POST, array('where' => array('mobile' => $_POST['mobile'])));
        $this->updateClient($status, '修改', true);
    }
}